<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>主机列表</title>
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/layui/layuiAdmin/css/admin.css" media="all">
</head>
<body>

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-form layui-card-header layuiadmin-card-header-auto" style="border-radius: 0;border-top: 4px solid #d2d2d2;">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">搜索条件</label>
                    <div class="layui-input-inline">
                        <select name="searchType">
                            <option value="macAddress">MAC地址</option>
                            <option value="hostName">主机名字</option>
                            <option value="ipAddress">IP地址</option>
                            <!-- 可以根据需要添加更多搜索条件 -->
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">关键词</label>
                    <div class="layui-input-inline">
                        <input type="text" name="keywords" placeholder="请输入查询内容" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-inline">
                    <button class="layui-btn layuiadmin-btn-hostadmin" lay-submit lay-filter="LAY-syshost-front-search">
                        <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                    </button>
                </div>
            </div>
        </div>
        <div class="layui-card-body">

            <div style="padding-bottom: 10px;">
                <button class="layui-btn layuiadmin-btn-hostadmin" data-type="batchdel">删除</button>
                <!--<button class="layui-btn layuiadmin-btn-hostadmin" data-type="add">添加</button> -->
                <button class="layui-btn layuiadmin-btn-hostadmin" data-type="refresh">刷新</button>
            </div>

            <!--  表格数据加载 -->
            <table id="LAY-host-manage" lay-filter="LAY-host-manage"></table>
            <!-- 新增开关模板 -->
            <script type="text/html" id="logSyncSwitchTpl">
                <input type="checkbox" name="logSync" lay-skin="switch" lay-text="开|关" lay-filter="logSyncSwitch"
                       data-macAddress="{{ d.macAddress }}"
                       data-id="{{ d.id }}"
                       data-host-name="{{ d.hostName }}"
                       data-ip-address="{{ d.ipAddress }}"
                       {{d.logSyncStatus === 1 ? 'checked' : ''}}>
                        {{ d.status === 0 ? 'disabled' : '' }}>

                <!--                       data-row-data="{{ JSON.stringify(d) }}">-->
            </script>
            <script type="text/html" id="table-hostadmin-webhost">
                <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="assets"><i class="layui-icon layui-icon-assets"></i>资产探测</a>

                <a class="layui-btn layui-btn layui-btn-xs" lay-event="detail"><i class="layui-icon layui-icon-detail"></i>资产详情</a>
                <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="threat"><i class="layui-icon layui-icon-assets"></i>风险发现</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
            </script>


            <!--  创建时间格式化处理 -->
            <script type="text/html" id="createTimeTpl">
                {{formatDate(d.createTime)}}
            </script>

            <!--  更新时间格式化处理 -->
            <script type="text/html" id="updateTimeTpl">
                {{formatDate(d.updateTime)}}
            </script>

        </div>
    </div>
</div>

<script src="/layui/layui.js"></script>
<script type="text/javascript">
    // 日期格式转换函数
    function formatDate(str) {
        if(str != null){
            var now = new Date(str);
            var year = now.getFullYear();  //取得4位数的年份
            var month = now.getMonth() + 1;  //取得日期中的月份，其中0表示1月，11表示12月
            var date = now.getDate();      //返回日期月份中的天数（1到31）
            var hours = now.getHours();
            var minutes = now.getMinutes();
            var seconds = now.getSeconds();
            return year + "-" + month + "-" + date +" "+hours+":"+minutes+":"+seconds;
        }
        return "";
    }
</script>
<script type="text/javascript">
    layui.config({
        base: '/layui/layuiAdmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['layer','table','form'], function(){
        var $ = layui.$
            ,form = layui.form
            ,layer = layui.layer
            ,table = layui.table;

        //加载table
        table.render({
            elem: '#LAY-host-manage'
            ,method: 'post'
            ,url:'/host/list' //后端接口
            ,headers: {
                'Authorization': localStorage.getItem('token')
            }
            ,width: 'auto'// 自适应宽度
            ,cellMinWidth: 80 //全局定义常规单元格的最小宽度
            ,title: '系统用户数据表'
            ,cols: [
                [
                    {type: 'checkbox', fixed: 'left'}
                    // ,{field:'id',title:'ID',width: 40}
                    ,{field:'logSync', title:'日志同步',width: 100, templet: '#logSyncSwitchTpl'}
                    ,{field:'macAddress', title:'MAC地址',width: 160}
                    ,{field:'hostName', title:'主机名字',width: 160}
                    ,{field:'ipAddress', title:'IP地址',width: 160,}
                    ,{field:'status', title:'状态',width: 80,templet:function (d){
                        if(d.status === 1){
                            return "<button class='layui-btn layui-btn-normal layui-btn-xs'>上线</button>";
                        }else if(d.status === 0){
                            return "<button class='layui-btn layui-btn-danger layui-btn-xs'>下线</button>";
                        }
                    }}
                    ,{field:'osType', title:'系统类型',width: 160,templet:function (d){
                        if(d.osType === 'Windows'){
                            return "<button class='layui-btn layui-btn-normal layui-btn-xs'>"+d.osType+"</button>";
                        }else if(d.osType === "Linux"){
                            return "<button class='layui-btn layui-btn layui-btn-xs'>"+d.osType+"</button>";
                        }else{
                            return "<button class='layui-btn layui-btn-danger layui-btn-xs'>"+d.osType+"</button>";
                        }
                    }}
                    ,{field:'osName', title:'系统版本',width: 160,}
                    ,{field:'osVersion', title:'系统版本号',width: 80,}
                    ,{field:'osBit', title:'位数',width: 80,}
                    ,{field:'cpuName', title:'CPU',width: 160,}

                    ,{field:'ram', title:'内存',width: 80,}

                    ,{field:'createTime', title:'采集时间',width: 160, templet:function (d){
                        return formatDate(d.createTime);
                    }}
                    ,{field:'updateTime', title:'上线时间',width: 160, templet: function (d){
                            return d.updateTime==null ? formatDate(d.createTime):formatDate(d.updateTime);
                    }}
                    ,{fixed: 'right', title:'操作', toolbar: '#table-hostadmin-webhost',width:320},
                ]]
            ,page: {
                curr: 1 //设定初始在第 5 页
                ,limit: 5 //设定初始每页显示 5 条
            },
            limits:[5,10,15,20]
        });
        // 监听日志同步开关事件
        // 监听日志同步开关事件
        form.on('switch(logSyncSwitch)', function(obj){
            var macAddress = $(this).attr('data-macAddress');
            var id = $(this).attr('data-id');
            var hostName = $(this).attr('data-host-name');
            var ipAddress = $(this).attr('data-ip-address');
            var isChecked = obj.elem.checked;
            console.log('macAddress:', macAddress);
            console.log('id:', id);
            console.log('hostName:', hostName);
            // 获取主机状态
            var status = $(this).closest('tr').find('[data-field="status"] button').text().trim();
            if (status === '下线') {
                layer.msg('主机不在线，无法操作', {icon: 5});
                // 恢复开关状态
                obj.elem.checked = !isChecked;
                form.render('checkbox');
                return;
            }

            // 发送状态变更请求
            $.ajax({
                url: "/host/updateLogSyncStatus",
                type: "post",
                headers: {
                    'Authorization': localStorage.getItem('token')
                },
                data: {
                    macAddress: macAddress,
                    status: obj.elem.checked ? 1 : 0
                },
                dataType: "json",
                success: function (res) {
                    if (res.code == 0) {
                        layer.msg(isChecked ? "已开启日志同步" : "已停止日志同步");

                        // 发送队列消息到后端
                        // $.ajax({
                        //     url: "/host/sendLogSyncMessage",
                        //     type: "post",
                        //     headers: {
                        //         'Authorization': localStorage.getItem('token')
                        //     },
                        //     data: {
                        //         macAddress: macAddress,
                        //         status: isChecked ? 1 : 0
                        //     },
                        //     dataType: "json",
                        //     success: function (res) {
                        //         if (res.code != 0) {
                        //             layer.msg(res.msg, {icon: 5});
                        //         }
                        //     }
                        // });
                    } else {
                        layer.msg(res.msg, {icon: 5});
                        // 恢复开关状态
                        data.elem.checked = !isChecked;
                        form.render('checkbox');
                    }
                },
                error: function() {
                    layer.msg("网络错误，请重试", {icon: 5});
                    // 恢复开关状态
                    data.elem.checked = !isChecked;
                    form.render('checkbox');
                }
            });
        });
        //监听行工具事件: 单行删除和修改
        table.on('tool(LAY-host-manage)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                layer.confirm('真的删除吗?', function(index){
                    $.ajax({
                        url:"/host/delete", //请求后端接口地址
                        type:"post", //请求方式get | post
                        headers: {
                            'Authorization': localStorage.getItem('token')
                        },
                        data:{ids:[data.id]}, //数据
                        dataType:"json", //后端返回参数类型
                        success:function (res){ //请求成功后回调函数res = JSONObject.toJSONString(resultMap)
                            if(res.code == 0){//成功
                                layer.msg(res.msg);//弹出提示
                                table.reload('LAY-host-manage'); //数据刷新
                                layer.close(index); //关闭弹层
                            }else {
                                layer.msg(res.msg,{icon: 5});//弹出提示
                            }
                        }
                    })
                });
            } else if(obj.event === 'assets'){
                layer.open({
                    type: 2
                    ,title: '探测资产'
                    ,skin: 'layui-layer-molv'
                    ,content: '/page/host/assets'
                    ,maxmin: true
                    ,area: ['480px', '310px']
                    ,btn: ['确定', '取消']
                    ,success: function (layero,index){ //弹出层加载之前执行
                        // 获取选中行的数据
                        // 获取弹出层的表单
                        var body = layer.getChildFrame("body",index);
                        var contentWindow = layero.find('iframe')[0].contentWindow;//得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                        // 获取编辑表单中用户名元素
                        // 数据回显到弹出的表单中
                        contentWindow.layui.form.val('layuiadmin-form-hostadmin', {
                            "id": data.id
                            ,"hostName": data.hostName
                            ,"macAddress": data.macAddress
                        });


                    }
                    ,yes: function (index,layero){
                        var iframeWindow = window['layui-layer-iframe'+ index]
                            ,submitID = 'LAY-host-front-submit'
                            ,submit = layero.find('iframe').contents().find('#'+ submitID);
                        //监听提交--隐藏按钮
                        iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
                            var field = data.field; //获取提交的字段
                            console.log(field);
                            // 通过Ajax方式将参数提交到后端--保存数据库中
                            $.ajax({
                                url:"/host/assetsDiscovery",
                                type:"post",
                                headers: {
                                    'Authorization': localStorage.getItem('token')
                                },
                                data:JSON.stringify(field),
                                contentType: "application/json;charset=utf-8", //提交参数类型为json格式
                                dataType:"json",
                                success:function (res){
                                    if(res.code == 0){//成功
                                        layer.msg(res.msg);//弹出提示
                                        table.reload('LAY-host-manage'); //数据刷新
                                        layer.close(index); //关闭弹层
                                    }else{//系统出问题
                                        layer.msg(res.msg,{icon: 5});//弹出提示
                                    }
                                }
                            })
                        });
                        submit.trigger('click');
                    }

                });
            }else if(obj.event === 'detail'){
                layer.open({
                    type: 2,
                    title: '资产详情',
                    skin: 'layui-layer-molv',
                    content: '/page/host/detail',
                    maxmin: true,
                    area: ['100%', '100%'],
                    success: function (layero, index) {
                        //layer.full(index);
                        var body = layer.getChildFrame('body', index);
                        var contentWindow = layero.find('iframe')[0].contentWindow;

                        contentWindow.layui.form.val('layuiadmin-form-hostadmin', {
                            "id": data.id
                            , "hostName": data.hostName
                            , "macAddress": data.macAddress
                            , "ipAddress":data.ipAddress
                            ,"osType":data.osType
                            ,"osName":data.osName
                            ,"ram":data.ram
                            ,"cpuName":data.cpuName
                        });
                        contentWindow.setMacAddress(data.macAddress);
                        // 根据mac地址查询对应的资产信息
                        // 可以在这里通过Ajax请求获取对应主机的资产探测结果
                        $.ajax({
                            url: '/host/detail',
                            type: 'post',
                            headers: {
                                'Authorization': localStorage.getItem('token')
                            },
                            data: { id: data.id },
                            dataType: 'json',
                            success: function (res) {
                                if (res.code == 0) {
                                    // 将数据显示在detail.html中
                                    contentWindow.showDetail(res.data);
                                } else {
                                    layer.msg(res.msg, { icon: 5 });
                                }
                            }
                        });
                    }
                });
            }
            else if(obj.event === 'threat'){
                layer.open({
                    type: 2
                    ,title: '风险发现'
                    ,skin: 'layui-layer-molv'
                    ,content: '/page/host/risk'
                    ,maxmin: true
                    ,area: ['480px', '310px']
                    ,btn: ['确定', '取消']
                    ,success: function (layero,index){ //弹出层加载之前执行
                        // 获取选中行的数据
                        // 获取弹出层的表单
                        var body = layer.getChildFrame("body",index);
                        var contentWindow = layero.find('iframe')[0].contentWindow;//得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                        // 获取编辑表单中用户名元素
                        // 数据回显到弹出的表单中
                        contentWindow.layui.form.val('layuiadmin-form-hostadmin', {
                            "id": data.id
                            ,"hostName": data.hostName
                            ,"macAddress": data.macAddress

                        });


                    }
                    ,yes: function (index,layero){
                        var iframeWindow = window['layui-layer-iframe'+ index]
                            ,submitID = 'LAY-host-front-submit'
                            ,submit = layero.find('iframe').contents().find('#'+ submitID);
                        //监听提交--隐藏按钮
                        iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
                            var field = data.field; //获取提交的字段
                            console.log(field);
                            // 通过Ajax方式将参数提交到后端--保存数据库中
                            $.ajax({
                                url:"/host/threatDiscovery",
                                type:"post",
                                headers: {
                                    'Authorization': localStorage.getItem('token')
                                },
                                data:JSON.stringify(field),
                                contentType: "application/json;charset=utf-8", //提交参数类型为json格式
                                dataType:"json",
                                success:function (res){
                                    if(res.code == 0){//成功
                                        layer.msg(res.msg);//弹出提示
                                        table.reload('LAY-host-manage'); //数据刷新
                                        layer.close(index); //关闭弹层
                                    }else{//系统出问题
                                        layer.msg(res.msg,{icon: 5});//弹出提示
                                    }
                                }
                            })
                        });
                        submit.trigger('click');
                    }

                });
            }
        });

        //监听搜索
        form.on('submit(LAY-syshost-front-search)', function(data){
            var field = data.field;
            //执行重载
            table.reload('LAY-host-manage', {
                url: '/host/list',
                method: "post",
                headers: {
                    'Authorization': localStorage.getItem('token')
                },
                where:{
                    searchField: field.searchType,
                    keywords: field.keywords
                }
            });
        });

        //事件 批量删除，添加主机
        var active = {
            batchdel: function(){
                var checkStatus = table.checkStatus('LAY-host-manage')
                    ,checkData = checkStatus.data; //得到选中的数据

                if(checkData.length == 0){
                    return layer.msg('请选择数据');
                }

                // 程序走到这里，表示已经有选中要删除的数据了。
                layer.confirm('确定删除吗？',function (){
                    var hostIds = new Array();
                    $.each(checkData,function (index,item){
                        hostIds.push(item.id);
                    })
                    // 提交给后端
                    $.ajax({
                        url:"/host/delete",
                        type:"post",
                        headers: {
                            'Authorization': localStorage.getItem('token')
                        },
                        data:{ids:hostIds},
                        dataType:"json",
                        success:function (res){
                            if(res.code == 0){//成功
                                layer.msg(res.msg);
                                table.reload('LAY-host-manage'); //数据刷新
                                layer.close(index); //关闭弹层
                            }else{
                                layer.msg(res.msg,{icon: 5});//弹出提示
                            }
                        }
                    })
                })
            }
            ,add: function(){
                layer.open({
                    type: 2
                    ,title: '添加用户'
                    ,skin: 'layui-layer-molv'
                    ,content: '/page/host/add'
                    ,maxmin: true
                    ,area: ['580px', '350px']
                    ,btn: ['确定', '取消']
                    ,yes: function (index,layero){
                        var iframeWindow = window['layui-layer-iframe'+ index]
                            ,submitID = 'LAY-host-front-submit'
                            ,submit = layero.find('iframe').contents().find('#'+ submitID);
                        //监听提交--隐藏按钮
                        iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
                            var field = data.field; //获取提交的字段
                            // 通过Ajax方式将参数提交到后端--保存数据库中
                            $.ajax({
                                url:"/host/save",
                                type:"post",
                                headers: {
                                    'Authorization': localStorage.getItem('token')
                                },
                                data:JSON.stringify(field),
                                contentType: "application/json;charset=utf-8", //提交参数类型为json格式
                                dataType:"json",
                                success:function (res){
                                    if(res.code === 0){//成功
                                        layer.msg(res.msg);//弹出提示
                                        table.reload('LAY-host-manage'); //数据刷新
                                        layer.close(index); //关闭弹层
                                    }else{//系统出问题
                                        layer.msg(res.msg,{icon: 5});//弹出提示
                                    }
                                }
                            })
                        });
                        submit.trigger('click');
                    }

                });
            }
            ,refresh: function(){
                table.reload('LAY-host-manage', {
                    url: '/host/list',
                    method: "post",
                    headers: {
                        'Authorization': localStorage.getItem('token')
                    }
                });
            }
        };

        $('.layui-btn.layuiadmin-btn-hostadmin').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

    });
</script>
</body>
</html>